import * as React from 'react';
import {
    View,
    TouchableOpacity,
    Text,
    Image,
    TextInput,
    SafeAreaView,
    Alert,
    DeviceEventEmitter,
} from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import DateTimePicker from '@react-native-community/datetimepicker';
import * as Animatable from 'react-native-animatable';
import { getUserInfo, updateUserById, userUploadAvatar } from '../../../../common/api/user';
import styles from './style';
import Back from '../../../../common/component/back';
import { launchCamera, launchImageLibrary, showImagePicker } from 'react-native-image-picker';
const carame = require('../../../../common/img/carame2.png');

class MineInfo extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            male: true,
            descLen: 0,
            modalShow: false,
            userInfo: {
                nickname: '',
                gender: 0,
                birthday: new Date(0),
                desc: '',
                _id: null,
                avatar: '',
            },
        };
    }

    componentDidMount() {
        this.getData();
    }
    // 页面销毁时发送通知
    // componentWillUnmount() {
    // DeviceEventEmitter.emit('RefreshMineData');
    // }
    getData = async () => {
        // const userInfo = await AsyncStorage.getItem('userInfo');

        AsyncStorage.getItem('userInfo', async (err, userInfo) => {
            if (err) {
                return Alert.alert(err);
            }
            if (userInfo) {
                setTimeout(() => {
                    const parsedUserInfo = JSON.parse(userInfo);
                    this.setState({
                        userInfo: parsedUserInfo,
                        descLen: parsedUserInfo.desc?.length || 0,
                    });
                }, 50);
            } else {
                const res = await getUserInfo();
                if (!res) {
                    return;
                }
                this.setState({
                    userInfo: res,
                    descLen: res.desc?.length || 0,
                });
            }
        });
    };
    /**
     * 日期选择onChange
     */
    onChange = (event, selectedDate) => {
        console.log({ selectedDate });
        const currentDate = selectedDate || this.state.userInfo.birthday;
        const { userInfo } = this.state;
        userInfo.birthday = currentDate;
        this.setState({
            userInfo,
        });
    };
    /**
     * 提交
     */
    submit = async () => {
        const { nickname, gender, birthday, desc, _id } = this.state.userInfo;
        if (!_id) {
            Alert.alert('保存失败', '请重新登录！');
        }
        await updateUserById(_id, { nickname, gender, birthday, desc });
        const res = await getUserInfo();
        this.setState({
            userInfo: res,
        });

        Alert.alert('保存成功');
        // DeviceEventEmitter.emit('RefreshMineData');

        // console.log(res);
    };

    uploadAvatar = () => {
        launchImageLibrary({ mediaType: 'photo', selectionLimit: 1 }, async res => {
            switch (res.errorCode) {
                case 'camera_unavailable':
                    return Alert.alert('相机不可用');
                case 'permission':
                    return Alert.alert('获取相册权限不足');
                case 'others':
                    return Alert.alert('相册获取失败');
                default:
                    break;
            }
            if (res.didCancel) {
                return '用户取消';
            }
            const formData = new FormData();

            // file是字段名，根据后端接受参数的名字来定,android上通过react-native-file-selector获取的path是不包含'file://'协议的，android上需要拼接协议为'file://'+path，而IOS则不需要,type可以是文件的MIME类型或者'multipart/form-data'
            for (let index = 0; index < res.assets.length; index++) {
                const element = res.assets[index];
                formData.append('files', {
                    uri: element.uri,
                    type: 'multipart/form-data',
                    name: element.fileName,
                });
            }
            await userUploadAvatar(formData);
            const userInfo = await getUserInfo();
            this.setState({ userInfo });
            DeviceEventEmitter.emit('ChangeUserAvatar');
            // DeviceEventEmitter.emit('RefreshMineData');
        });
    };
    render() {
        const { navigation } = this.props;
        const { userInfo } = this.state;
        return (
            <SafeAreaView style={styles.container}>
                <Back navigation={navigation} />
                <View style={styles.content}>
                    <View style={styles.top}>
                        <Text style={styles.title}>编辑资料</Text>
                        <TouchableOpacity style={styles.topImage} onPress={this.uploadAvatar}>
                            <Image
                                style={{ width: '100%', height: '100%', borderRadius: 30 }}
                                source={{
                                    uri:
                                        userInfo.avatar ||
                                        'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic4.zhimg.com%2F50%2Fv2-16898564e0a7dfb0eb1f2072dae62f3f_hd.jpg&refer=http%3A%2F%2Fpic4.zhimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1613130485&t=9adfc5111d4292e9d98bad6d928eaa0f',
                                }}
                            />

                            <View style={styles.topCarameImgGroup}>
                                <View style={styles.topCameraRow}>
                                    <Image source={carame} style={{ width: 16, height: 16 }} />
                                </View>
                            </View>
                        </TouchableOpacity>
                    </View>

                    <View style={styles.infoContent}>
                        <View style={styles.infoItem}>
                            <Text style={styles.infoItemTitle}>昵称</Text>
                            <TextInput
                                style={styles.infoItemDesc}
                                onChangeText={text => {
                                    userInfo.nickname = text;
                                    this.setState({ userInfo });
                                }}
                                value={this.state.userInfo.nickname}
                                placeholder="请输入昵称"
                                placeholderTextColor="#999"
                            />
                        </View>
                        <View style={[styles.infoItem, styles.infoItemSex]}>
                            <Text style={styles.infoItemTitle}>性别</Text>
                            <TouchableOpacity
                                style={[styles.sexBtn, userInfo.gender !== 1 && { backgroundColor: 'white' }]}
                                onPress={() => {
                                    userInfo.gender = 1;
                                    this.setState({ userInfo });
                                }}
                            >
                                <Text style={[styles.sexText, userInfo.gender !== 1 && { color: 'black' }]}>
                                    男
                                </Text>
                            </TouchableOpacity>
                            <TouchableOpacity
                                style={[styles.sexBtn, userInfo.gender !== 2 && { backgroundColor: 'white' }]}
                                onPress={() => {
                                    userInfo.gender = 2;
                                    this.setState({ userInfo });
                                }}
                            >
                                <Text style={[styles.sexText, userInfo.gender !== 2 && { color: 'black' }]}>
                                    女
                                </Text>
                            </TouchableOpacity>
                        </View>
                        <View style={styles.birthdayItem}>
                            <Text style={styles.infoItemTitle}>生日</Text>
                            {/* 可使用弹窗 */}
                            <DateTimePicker
                                locale="zh-CN"
                                // testID="dateTimePicker"
                                value={new Date(userInfo.birthday) || new Date(0)}
                                is24Hour={true}
                                display="spinner"
                                themeVariant="light"
                                maximumDate={new Date()}
                                style={styles.birthday}
                                onChange={this.onChange}
                            />
                        </View>

                        <View style={styles.infoItem}>
                            <Text style={styles.infoItemTitle}>签名</Text>
                            <TextInput
                                maxLength={15}
                                placeholder="请输入签名"
                                value={this.state.userInfo.desc}
                                style={(styles.infoItemDesc, { width: 260 })}
                                onChangeText={text => {
                                    userInfo.desc = text;
                                    this.setState({ descLen: text.length, userInfo });
                                }}
                            />
                            <Text style={{ fontSize: 12 }}>{this.state.descLen}</Text>
                            <Text style={{ fontSize: 12, color: 'rgb(153, 153, 153)' }}>/15</Text>
                        </View>
                        <View style={styles.buttonGroup}>
                            <TouchableOpacity onPress={this.submit}>
                                <Animatable.View
                                    style={[styles.viewBorder, styles.saveButton]}
                                    animation="slideInUp"
                                >
                                    <Text style={styles.textSave}>保存</Text>
                                </Animatable.View>
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>
            </SafeAreaView>
        );
    }
}

export default MineInfo;
